package com.h3c.gm.common.utils

import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import org.apache.commons.lang3.builder.ToStringBuilder
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory

/**
 * Created by d14287 on 2017/7/7.
 */
class HttpUtils {
    static Logger logger = LoggerFactory.getLogger(HttpUtils.class)

    static Optional<JSONArray> httpGet(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault()
        try {
            HttpGet get = new HttpGet(url)
            CloseableHttpResponse response = httpClient.execute(get)
            logger.info("url:" + url + " - status:" + ToStringBuilder.reflectionToString(response.getStatusLine()))
            if (response.getStatusLine().getStatusCode() == 200) {
                String entityStr = EntityUtils.toString(response.getEntity())
                JSONArray arrays = JSONObject.parseArray(entityStr)
                return Optional.of(arrays)
            }
            response.close()
        } catch (IOException e) {
            logger.error("httpUtils happend error", e)
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close()
                }
            } catch (IOException e) {
                logger.error(e)
            }
        }
        return Optional.empty()
    }
}
